package net.learn2develop.SMSMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts.People;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity {
	private static final int PICK_CONTACT = 0;
	Button btnGetContact;
	Button btnSendSMS;
	EditText txtPhoneNo;
	EditText txtMessage;
	EditText txtPassword;
	private String name;
	private String phoneNumber;
	private String emailAddress;
	private String poBox;
	private String street;
	private String city;
	private String state;
	private String postalCode;
	private String country;
	private String type;
	
	private AESCrypto aesCrypt;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sendsms);

		this.aesCrypt =  new AESCrypto();
		
		btnGetContact = (Button) findViewById(R.id.btnGetContact);
		btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
		txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
		txtMessage = (EditText) findViewById(R.id.txtMessage);
		txtPassword = (EditText) findViewById(R.id.txtPassword);

		btnGetContact.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// This code works for Android UNDER 2.2
				//Intent intent = new Intent(Intent.ACTION_PICK, People.CONTENT_URI);
				//startActivityForResult(intent, PICK_CONTACT);
				
				// This code works for Android ABOVE 2.2
				Intent intentContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); 
			    startActivityForResult(intentContact, PICK_CONTACT);
				
			}
		});
		
		btnSendSMS.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				String phoneNo = txtPhoneNo.getText().toString();
				String message = txtMessage.getText().toString();
				String password = txtPassword.getText().toString();
				if (phoneNo.length() > 0 && message.length() > 0
						&& password.length() > 0)
					sendSMS(phoneNo, message, password);
				else
					Toast.makeText(getBaseContext(),
							"Please enter phone number, password and message.",
							Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) 
	{

	  if (requestCode == PICK_CONTACT)
	  {         
	    getContactInfo(intent);         
	    txtPhoneNo.setText(phoneNumber);
	  }
	}//onActivityResult
	
	protected void getContactInfo(Intent intent)
	{

	   Cursor cursor =  managedQuery(intent.getData(), null, null, null, null);      
	   while (cursor.moveToNext()) 
	   {           
	       String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
	       name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

	       String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

	       if ( hasPhone.equalsIgnoreCase("1"))
	           hasPhone = "true";
	       else
	           hasPhone = "false" ;

	       if (Boolean.parseBoolean(hasPhone)) 
	       {
	        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null);
	        while (phones.moveToNext()) 
	        {
	          phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
	        }
	        phones.close();
	       }

	       // Find Email Addresses
	       Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId,null, null);
	       while (emails.moveToNext()) 
	       {
	        emailAddress = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
	       }
	       emails.close();

	    Cursor address = getContentResolver().query(
	                ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
	                null,
	                ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId,
	                null, null);
	    while (address.moveToNext()) 
	    { 
	      // These are all private class variables, don't forget to create them.
	      poBox      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
	      street     = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
	      city       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
	      state      = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
	      postalCode = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
	      country    = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
	      type       = address.getString(address.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
	    }  //address.moveToNext()   
	  }  //while (cursor.moveToNext())        
	   cursor.close();
	}//getContactInfo
	
//	@Override
//	public void onActivityResult(int reqCode, int resultCode, Intent data) {
//	  super.onActivityResult(reqCode, resultCode, data);
//
//	  switch (reqCode) {
//	    case (PICK_CONTACT) :
//	      if (resultCode == Activity.RESULT_OK) {
//	        Uri contactData = data.getData();
//	        Cursor c =  managedQuery(contactData, null, null, null, null);
//	        if (c.moveToFirst()) {
//	          String number = c.getString(c.getColumnIndexOrThrow(People.NUMBER));
//	          txtPhoneNo.setText(number);
//	        }
//	      }
//	      break;
//	  }
//	}
	
	// --- sends an SMS message to another device---
	public void sendSMS(String phoneNumber, String message, String password) {
		String SENT = "SMS_SENT";
		String DELIVERED = "SMS_DELIVERED";

		PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
				SENT), 0);
		PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
				new Intent(DELIVERED), 0);

		// ---when the SMS has been sent---
		final SMS s = this;
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS sent",
							Toast.LENGTH_LONG).show();
					try {
						Thread.currentThread();
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						s.finish();
					}
					break;
				case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
					Toast.makeText(getBaseContext(), "Generic failure",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NO_SERVICE:
					Toast.makeText(getBaseContext(), "No service",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_NULL_PDU:
					Toast.makeText(getBaseContext(), "Null PDU",
							Toast.LENGTH_SHORT).show();
					break;
				case SmsManager.RESULT_ERROR_RADIO_OFF:
					Toast.makeText(getBaseContext(), "Radio off",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(SENT));

		// ---when the SMS has been delivered---
		registerReceiver(new BroadcastReceiver() {
			@Override
			public void onReceive(Context arg0, Intent arg1) {
				switch (getResultCode()) {
				case Activity.RESULT_OK:
					Toast.makeText(getBaseContext(), "SMS delivered",
							Toast.LENGTH_SHORT).show();
					break;
				case Activity.RESULT_CANCELED:
					Toast.makeText(getBaseContext(), "SMS not delivered",
							Toast.LENGTH_SHORT).show();
					break;
				}
			}
		}, new IntentFilter(DELIVERED));

		SmsManager sms = SmsManager.getDefault();
		String encrypted = "";
		String decrypted = "";
		try {
			if (aesCrypt == null) aesCrypt = new AESCrypto();
			encrypted = SimpleCrypto.toHex((aesCrypt.Encrypt(message.getBytes(), password)));
			
			byte[] encryptedByte = SimpleCrypto.toByte(encrypted);
			decrypted = SimpleCrypto.toHex(aesCrypt.Decrypt(message.length(), encryptedByte, password));
			
			//encrypted = SimpleCrypto.encrypt(password, message);
		} catch (Exception e) {
			Log.e("leon","ERROR: " + e.getMessage());
			//System.err.println("ERROR: " + e.getMessage());
			// send clear text
			encrypted = "Cleartext: " + message;
		}
		sms.sendTextMessage(phoneNumber, null, encrypted, sentPI, deliveredPI);
	}
}